<?php
// 微信支付配置
$appid = 'wx476ad85e3f8d4026'; // 替换为你的微信公众号或者小程序的 appid
$mch_id = '1648407769'; // 替换为你的微信支付商户号
$key = 'yzs10131594561594560zxcvbnmasdfr'; // 替换为你的微信支付 API 密钥
$notify_url = 'your_notify_url'; // 替换为你的支付结果通知回调地址

// 生成随机字符串
function getNonceStr($length = 32)
{
    $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}

// 生成签名
function getSign($params, $key)
{
    ksort($params);
    $string = '';
    foreach ($params as $k => $v) {
        if ($k != 'sign' && $v != '' && !is_array($v)) {
            $string .= $k . '=' . $v . '&';
        }
    }
    $string = rtrim($string, '&');
    $string = $string . '&key=' . $key;
    return strtoupper(md5($string));
}

// 数组转 XML
function arrayToXml($arr)
{
    $xml = "<xml>";
    foreach ($arr as $key => $val) {
        if (is_numeric($val)) {
            $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
        } else {
            $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
    }
    $xml .= "</xml>";
    return $xml;
}

// XML 转数组
function xmlToArray($xml)
{
    libxml_disable_entity_loader(true);
    $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $values;
}

// 发送 HTTP POST 请求
function httpPost($url, $data)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Curl error: ' . curl_error($ch);
    }
    curl_close($ch);
    return $result;
}

// 统一下单请求
$params = [
    'appid' => $appid,
    'mch_id' => $mch_id,
    'nonce_str' => getNonceStr(),
    'body' => '测试商品', // 商品描述
    'out_trade_no' => date('YmdHis') . rand(1000, 9999), // 商户订单号，需保证唯一性
    'total_fee' => 1, // 订单总金额，单位为分
    'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
    'notify_url' => $notify_url,
    'trade_type' => 'NATIVE'
];

$params['sign'] = getSign($params, $key);
$xmlData = arrayToXml($params);

$unifiedOrderUrl = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
$responseXml = httpPost($unifiedOrderUrl, $xmlData);
$response = xmlToArray($responseXml);

if ($response['return_code'] === 'SUCCESS' && $response['result_code'] === 'SUCCESS') {
    $codeUrl = $response['code_url'];
    echo "支付二维码链接: " . $codeUrl;
    // 你可以使用第三方库（如 PHP QR Code）根据 $codeUrl 生成二维码图片
} else {
    echo "错误信息: " . ($response['err_code_des'] ?? $response['return_msg']);
}